//! PlaySpace.debug.js
//

(function() {

Type.registerNamespace('PlaySpace.Classes');

////////////////////////////////////////////////////////////////////////////////
// GigForms

GigForms = function GigForms() {
    /// <field name="keysKey" type="String" static="true">
    /// </field>
    /// <field name="isPwKey" type="String" static="true">
    /// </field>
    /// <field name="validateException" type="String" static="true">
    /// </field>
    /// <field name="_cloneProps" type="Array" elementType="String" static="true">
    /// </field>
}
GigForms.validate = function GigForms$validate(el, fn) {
    /// <param name="el" type="jQueryObject">
    /// </param>
    /// <param name="fn" type="Function">
    /// </param>
    /// <returns type="String"></returns>
    var v = el.getFValueString();
    var t = el.attr('title');
    if (String.isNullOrEmpty(v)) {
        Ask.ok(String.format('Please provide a value for "{0}"', (t || el.attr('id') || 'unknown')));
        return null;
    }
    if (fn != null) {
        if (!fn(v)) {
            return null;
        }
    }
    return v;
}
GigForms.validateThrow = function GigForms$validateThrow(el, fn) {
    /// <param name="el" type="jQueryObject">
    /// </param>
    /// <param name="fn" type="Function">
    /// </param>
    /// <returns type="String"></returns>
    var v = GigForms.validate(el, fn);
    if (v == null) {
        throw new Error('ValidateException');
    }
    return v;
}
GigForms.notEmpty = function GigForms$notEmpty(txt) {
    /// <param name="txt" type="String">
    /// </param>
    /// <returns type="Boolean"></returns>
    return !String.isNullOrEmpty(txt);
}
GigForms.sendTheMail = function GigForms$sendTheMail(mail, confirm) {
    /// <param name="mail" type="Object">
    /// </param>
    /// <param name="confirm" type="Boolean">
    /// </param>
    if (Nsb.Storage.getLocal('DevNoEmail')) {
        return;
    }
    var awx = new Await().addAw(CloudMail.sendMailAw, mail);
    if (confirm) {
        awx.addDx(function() {
            Ask.ok('Your request has been received.<br><br>&nbsp;&nbsp;&nbsp;&nbsp;Thank you!');
        });
    }
    awx.commit();
}
GigForms.initializePageInput = function GigForms$initializePageInput() {
    if (ThemeBase.publishing || (Nsb.Storage.getLocal(ThemeYoshi.get_curatingKey()) && !ThemeYoshi.get_currentPage().Admin)) {
        return;
    }
    var gigs = $('#PageGigs');
    $('input[type=text],textarea', gigs).each(function(i, domEl) {
        var ths = $(domEl);
        if (ths.val().toLowerCase().indexOf('password') !== -1) {
            var id = ths.attr('id');
            var newpw = $("<input type='password'/>").insertBefore(ths);
            newpw.addClass(ths.attr('className'));
            newpw.attr('title', ths.val());
            newpw.val('');
            Css.clone(ths, newpw);
            ths.removeAttr('id');
            newpw.attr('id', id);
            GigForms.labelBehind(newpw, ths);
            ths = newpw;
        }
        else {
            ths.attr('title', ths.val());
            ths.val('');
            GigForms.labelBehind(ths);
        }
        ths.addClass('UserInput');
        ths.keydown(function(e) {
            if (e.which === 13) {
                $('.DefaultButton').first().click();
                DomElement.cancelEvent(e);
            }
        });
    });
}
GigForms.setDeef = function GigForms$setDeef(el) {
    /// <param name="el" type="jQueryObject">
    /// </param>
    el.val('').trigger('myInit');
}
GigForms.labelBehind = function GigForms$labelBehind(el, use) {
    /// <param name="el" type="jQueryObject">
    /// </param>
    /// <param name="use" type="jQueryObject">
    /// </param>
    if (ThemeBase.publishing) {
        return;
    }
    var c1 = Css.fade(el.css('color'), 0.4);
    var c2 = Css.fade(el.css('color'), 0.75);
    var label = use;
    if (use == null) {
        label = $("<input type='text'/>");
        Css.clone(el, label);
    }
    label.insertBefore(el).addClass('LblBhd').val(el.attr('title')).css('position', 'absolute').removeAttr('tabindex').focusin(function(e) {
        el.reFocus();
        DomElement.cancelEvent(e);
    });
    if (!$.browser.msie) {
        label.attr('disabled', 'disabled');
    }
    el.bind('myInit focusout', function(e) {
        GigForms.toggleLabel(e, c1);
    }).bind('focusin keydown paste input', function(e) {
        GigForms.toggleLabel(e, c2);
    }).data('bgcolor', el.css('background-color'));
    el.css({ 'background-color': 'transparent' });
    var p = el.position();
    label.css({ color: c1, top: p.top, left: p.left, margin: 0, 'z-index': -1 });
    el.trigger('myInit');
}
GigForms.toggleLabel = function GigForms$toggleLabel(e, color) {
    /// <param name="e" type="jQueryEvent">
    /// </param>
    /// <param name="color" type="String">
    /// </param>
    var input = $(e.target);
    window.setTimeout(function() {
        var v = input.val();
        if (String.isNullOrEmpty(v)) {
            input.css('background-color', 'transparent');
            input.prev('.LblBhd').css('color', color).show();
        }
        else {
            input.css('background-color', input.data('bgcolor'));
            input.prev('.LblBhd').hide();
        }
    }, 0);
}


////////////////////////////////////////////////////////////////////////////////
// LogsPage

LogsPage = function LogsPage() {
    /// <field name="_headers" type="Object" static="true">
    /// </field>
    /// <field name="_logSite" type="String" static="true">
    /// </field>
}
LogsPage.Page = function LogsPage$Page() {
    var lg = Nsb.Storage.getSession('LogSite');
    if (lg != null) {
        if (lg === 'root') {
            LogsPage._logSite = Uri.join('../../', ThemeBase.appPath);
        }
        else {
            LogsPage._logSite = Uri.join('../../spaces/', lg, ThemeBase.appPath);
        }
    }
    LogsPage.makeTabBtn('#ErrorLogBtn', Uri.join(LogsPage._logSite, 'db/logs/errors.txt')).click();
    LogsPage.makeTabBtn('#BuildLogBtn', Uri.join(LogsPage._logSite, 'db/logs/build.txt'));
    LogsPage.makeTabBtn('#EventLogBtn', Uri.join(LogsPage._logSite, 'db/logs/events.txt'));
    LogsPage.makeTabBtn('#MasterLogBtn', Uri.join('/', ThemeBase.appPath, 'db/masterlogs/errors.txt'));
    if (lg != null) {
        $('#CreatorLogs').addClass('SpaceBtn').click(function() {
            Nsb.Storage.removeSession('LogSite');
            ThemeYoshi.reloadPage();
        });
    }
    else {
        $('#CreatorLogs').hide();
    }
    $('#SiteName').html(lg || ThemeBase.get_baseName());
}
LogsPage.makeTabBtn = function LogsPage$makeTabBtn(select, path) {
    /// <param name="select" type="String">
    /// </param>
    /// <param name="path" type="String">
    /// </param>
    /// <returns type="jQueryObject"></returns>
    return $(select).closest('.Gig').addClass('LogTabBtn').css({ 'background-color': '', color: '', 'border-color': '', 'border-style': '' }).click(function(e) {
        $('.LogTabBtn').removeClass('Selected');
        LogsPage.showLogAw(Await.get_asyncAw(), '#ErrorLogs', path);
        $(e.target).closest('.Gig').addClass('Selected');
    });
}
LogsPage.showLogAw = function LogsPage$showLogAw(awp, select, path) {
    /// <param name="awp" type="Await">
    /// </param>
    /// <param name="select" type="String">
    /// </param>
    /// <param name="path" type="String">
    /// </param>
    new Await().addAw(FileBlobBase.retrieveBlobStringAw, '', path, { allowEmpty: true }).handleDl(Exceptions.blobLoadError, function(aw) {
        $(select).empty();
        aw.finish();
    }).addDx(function(aw) {
        var el = $(select);
        var content = aw.get_result();
        if (String.isNullOrEmpty(content)) {
            el.empty();
            return;
        }
        var list = JSON.parse('[' + content + ']');
        list.reverse();
        el.empty().closest('.Gig').addClass('LogView');
        var box = $("<div class='TableDiv'/>").appendTo(el);
        var table = $('<table/>').appendTo(box);
        var head = $('<thead/>').appendTo(table);
        var body = $('<tbody/>').appendTo(table);
        var infobox = $("<div class='InfoBox'/>").appendTo(el).html(path);
        $("<img src='" + Uri.img('Common/close20.png') + "' class='DelBtn'/>").appendTo(infobox).attr('title', String.format('delete {0} log', path)).click(function() {
            LogsPage.deleteLog(path);
        });
        var tt = $('<tr/>').appendTo(head);
        var $dict1 = LogsPage._headers;
        for (var $key2 in $dict1) {
            var p = { key: $key2, value: $dict1[$key2] };
            $('<th/>').appendTo(tt).html(p.value);
        }
        var $enum3 = ss.IEnumerator.getEnumerator(list);
        while ($enum3.moveNext()) {
            var li = $enum3.current;
            var tr = $('<tr/>').appendTo(body);
            var $dict4 = LogsPage._headers;
            for (var $key5 in $dict4) {
                var p = { key: $key5, value: $dict4[$key5] };
                if (p.key === 'd') {
                    var dd = new Date(li.t);
                    $('<td>').appendTo(tr).html(dd.format('ddd MMM dd yyyy hh:mm:ss tt'));
                }
                else {
                    $('<td>').appendTo(tr).html(li[p.key].toString());
                }
            }
        }
    }).commit(awp);
}
LogsPage.deleteLog = function LogsPage$deleteLog(path) {
    /// <param name="path" type="String">
    /// </param>
    new Await().addAw(ss.Delegate.create(new Ask(), new Ask().okCancelAw), ThemeYoshi.forSure).addAw(DomElement.requireResultAw, true).addAw(FileBlobBase.deleteItemAw, '', path).addDx(function() {
        ThemeYoshi.reloadPage();
    }).commit();
}


////////////////////////////////////////////////////////////////////////////////
// PlaySpace.Classes.LogItem

PlaySpace.Classes.LogItem = function PlaySpace_Classes_LogItem() {
    /// <field name="b" type="String">
    /// </field>
    /// <field name="d" type="String">
    /// </field>
    /// <field name="e" type="String">
    /// </field>
    /// <field name="i" type="String">
    /// </field>
    /// <field name="m" type="String">
    /// </field>
    /// <field name="t" type="Number" integer="true">
    /// </field>
    /// <field name="u" type="String">
    /// </field>
}
PlaySpace.Classes.LogItem.prototype = {
    b: null,
    d: null,
    e: null,
    i: null,
    m: null,
    t: 0,
    u: null
}


////////////////////////////////////////////////////////////////////////////////
// Scroller

Scroller = function Scroller() {
}


////////////////////////////////////////////////////////////////////////////////
// Site

Site = function Site() {
    /// <field name="_ourEmail" type="String" static="true">
    /// </field>
    /// <field name="spacesPath" type="String" static="true">
    /// </field>
    /// <field name="passwordMatchMsg" type="String" static="true">
    /// </field>
    /// <field name="spaceNameShortMsg" type="String" static="true">
    /// </field>
    /// <field name="spaceNameLongMsg" type="String" static="true">
    /// </field>
    /// <field name="spaceNameLowerMsg" type="String" static="true">
    /// </field>
    /// <field name="spaceNameLettersMsg" type="String" static="true">
    /// </field>
    /// <field name="emailValidMsg" type="String" static="true">
    /// </field>
    /// <field name="passwordLengthMsg" type="String" static="true">
    /// </field>
    /// <field name="incorrectMathMsg" type="String" static="true">
    /// </field>
    /// <field name="_sendTo" type="String" static="true">
    /// </field>
    /// <field name="map" type="DirMap" static="true">
    /// </field>
    /// <field name="_validateEl" type="jQueryObject" static="true">
    /// </field>
}
Site.HomePage = function Site$HomePage() {
    $('#CreateButton').addClass('DefaultButton').click(function() {
        try {
            var csi = new CreateSpaceItem();
            csi.nameEl = $('#SpaceName');
            csi.emailEl = $('#Email');
            csi.password1El = $('#Password');
            csi.password2El = $('#PasswordAgain');
            csi.name = GigForms.validateThrow(csi.nameEl);
            Site._validateSpaceNameThrow(csi);
            csi.email = GigForms.validateThrow(csi.emailEl);
            Site._validateEmailAddrThrow(csi);
            csi.password1 = GigForms.validateThrow(csi.password1El);
            Site._validatePwThrow(csi);
            csi.password2 = GigForms.validateThrow(csi.password2El);
            if (csi.password1 !== csi.password2) {
                GigForms.setDeef(csi.password1El);
                GigForms.setDeef(csi.password2El);
                Ask.ok("passwords don't match");
                return;
            }
            Site._validateMath();
            new Await().addAw(Site._verifySpaceAvailableAw, csi.name).addAw(DomElement.requireResultAw, true).addDl(function(aw) {
                Site.createSpaceAw(aw, csi);
            }).commit();
        }
        catch (ex) {
            if (ex.message !== 'ValidateException') {
                throw ex;
            }
        }
    }).keydown(function(e) {
        if (e.which === 9) {
            $('#SpaceName').focus();
            DomElement.cancelEvent(e);
        }
    });
    Site._createMath();
    GigForms.initializePageInput();
    $(document).bind('PageDefaultFocus', Site.pageDefaultFocusEv).trigger('PageDefaultFocus');
}
Site.pageDefaultFocusEv = function Site$pageDefaultFocusEv(e) {
    /// <param name="e" type="jQueryEvent">
    /// </param>
    var el = Site._validateEl || $('#SpaceName');
    if (Site._validateEl == null) {
        $('input').each(function(i, domEl) {
            var t = $(domEl);
            if (String.isNullOrEmpty(t.val().trim())) {
                el = t;
                return false;
            }
            return true;
        });
    }
    el.reFocus();
}
Site.SitesPage = function Site$SitesPage() {
    Spaces.page();
}
Site.spaceDelUx = function Site$spaceDelUx(site) {
    /// <param name="site" type="String">
    /// </param>
    /// <returns type="Function"></returns>
    var start = new Date().getTime();
    return function(e) {
        var awx = new Await();
        if (!e.altKey) {
            awx.addAw(ss.Delegate.create(new Ask(), new Ask().okCancelAw), { Msg: ThemeYoshi.forSure }).addAw(DomElement.requireResultAw, true);
        }
        awx.addDl(function(aw) {
            FileBlobBase.emptyFolderAw(aw, Uri.join('../../spaces', site), true);
        }).addDx(function() {
            Site.SitesPage();
        }).addDx(function() {
            Exceptions.SaveLog('build', String.format('deleted - space {0} time={1}ms', site, new Date().getTime() - start));
        }).commit();
    };
}
Site._sendMeMail = function Site$_sendMeMail(csi) {
    /// <param name="csi" type="CreateSpaceItem">
    /// </param>
    var mail = {};
    var smd = mail;
    var href = Uri.addPair('http://www.playnexus.com/spaces/' + csi.name + '/' + ThemeBase.appPath + '/activate.php', 'act', csi.activateId);
    smd.to = Site._sendTo;
    smd.subject = 'New playspace created';
    smd.from = csi.email;
    smd.content = '';
    smd.content += 'Space name: ' + csi.name + '<br>';
    smd.content += 'Space email: ' + csi.email + '<br>';
    smd.content += '<br>';
    smd.content += String.format("Click this link to activate: <a href='{0}'>{1}</a>", href, href);
    GigForms.sendTheMail(mail, false);
}
Site._sendThemMail = function Site$_sendThemMail(csi) {
    /// <param name="csi" type="CreateSpaceItem">
    /// </param>
    var mail = {};
    var smd = mail;
    var href = Uri.addPair('http://www.playnexus.com/spaces/' + csi.name + '/' + ThemeBase.appPath + '/activate.php', 'act', csi.activateId);
    smd.to = csi.email;
    smd.subject = 'Activate your PlayNexus Playspace';
    smd.from = 'playspaces@playnexus.com';
    smd.content = '';
    smd.content += 'PlayNexus Playspace name: ' + csi.name + '<br>';
    smd.content += 'Owner: ' + csi.email + '<br>';
    smd.content += '<br>';
    smd.content += String.format("Click this link to activate: <a href='{0}'>{1}</a>", href, href);
    GigForms.sendTheMail(mail, false);
}
Site._validateSpaceNameThrow = function Site$_validateSpaceNameThrow(csi) {
    /// <param name="csi" type="CreateSpaceItem">
    /// </param>
    Site._validateEl = csi.nameEl;
    var txt = csi.name;
    if (txt.length < 4) {
        Ask.ok('space name must be at least 4 characters long');
        throw new Error('ValidateException');
    }
    if (txt.length >= 20) {
        Ask.ok('space name must be less than 20 characters long');
        throw new Error('ValidateException');
    }
    if (txt.toLowerCase() !== txt) {
        Ask.ok('space name must be all lower case');
        throw new Error('ValidateException');
    }
    if (!(/^[a-z][a-z0-9_]+$/).test(txt)) {
        Ask.ok('space name can only contain letters, numbers, and underscore and must start with a letter');
        throw new Error('ValidateException');
    }
}
Site._validateEmailAddrThrow = function Site$_validateEmailAddrThrow(csi) {
    /// <param name="csi" type="CreateSpaceItem">
    /// </param>
    Site._validateEl = csi.emailEl;
    if (!Rx.emailFilter.test(csi.email)) {
        Ask.ok('please enter a valid email address');
        throw new Error('ValidateException');
    }
}
Site._validatePwThrow = function Site$_validatePwThrow(csi) {
    /// <param name="csi" type="CreateSpaceItem">
    /// </param>
    Site._validateEl = csi.password1El;
    if (csi.password1.length < 8) {
        GigForms.setDeef(csi.password1El);
        GigForms.setDeef(csi.password2El);
        Ask.ok('password must be at least 8 characters long');
        throw new Error('ValidateException');
    }
}
Site._createMath = function Site$_createMath() {
    var mpEl = $('#MathProblem');
    var mrEl = $('#MathResult');
    var r;
    var ot;
    do {
        var m1 = Formulas.randomOf(9);
        var m2 = Formulas.randomOf(9);
        var m3 = Formulas.randomOf(9);
        var o1 = (!Formulas.randomOf(1)) ? '+' : '+';
        var o2 = (!Formulas.randomOf(1)) ? '+' : '+';
        r = m1;
        r = (o1 === '+') ? r + m2 : r - m2;
        r = (o2 === '+') ? r + m3 : r - m3;
        ot = String.format('{0} {1} {2} {3} {4} =', m1, o1, m2, o2, m3);
    } while (r < 0);
    mrEl.data('mr', r);
    mpEl.html(ot);
}
Site._validateMath = function Site$_validateMath() {
    Site._validateEl = $('#MathResult');
    var mrEl = $('#MathResult');
    var mr = mrEl.data('mr');
    GigForms.validateThrow(mrEl);
    var result = Number.parse(mrEl.val());
    if (result === -9999 && Nsb.Storage.getLocal(ThemeBase.devServerKey)) {
        return;
    }
    if (result !== mr) {
        Site._createMath();
        GigForms.setDeef(mrEl);
        Ask.ok('incorrect math result');
        throw new Error('ValidateException');
    }
}
Site._verifySpaceAvailableAw = function Site$_verifySpaceAvailableAw(awp, name) {
    /// <param name="awp" type="Await">
    /// </param>
    /// <param name="name" type="String">
    /// </param>
    Site._validateEl = $('#CreateButton');
    new Await().addAw(Site._ckSpaceAvailAw, name).handleDl(Exceptions.blobLoadError, Await.rethrowAw).addDx(function(aw) {
        var ic = aw.get_result();
        if (!ic) {
            Ask.ok(String.format('The space "{0}" is not available', name));
        }
    }).commit(awp);
}
Site._ckSpaceAvailAw = function Site$_ckSpaceAvailAw(awp, name) {
    /// <param name="awp" type="Await">
    /// </param>
    /// <param name="name" type="String">
    /// </param>
    var args = { name: name };
    var options = {};
    options.url = Uri.app('ph/file.ckcreate.php');
    options.dataType = 'json';
    options.data = args;
    options.type = 'GET';
    options.success = function(data, textStatus, request1) {
        var result = data;
        awp.set_result(result['result']);
        awp.done();
    };
    options.error = function(request, textStatus, error) {
        Inform.error(String.format('Error verifying space {0}, {1} {2}', name, textStatus, error));
        awp.handle(new Error(Exceptions.blobLoadError));
    };
    $.ajax(options);
}
Site.createSpaceAw = function Site$createSpaceAw(awp, csi) {
    /// <param name="awp" type="Await">
    /// </param>
    /// <param name="csi" type="CreateSpaceItem">
    /// </param>
    var start = new Date().getTime();
    var msg = String.format(' - creating space name={0}', csi.name);
    Inform.event('Site.CreateSpaceAw', msg);
    Exceptions.SaveLog('build', 'beginning' + msg);
    Cluster.spinner(true);
    csi.createTime = new Date().getTime();
    Uri.bumpVersion();
    var args = { spaceName: csi.name, curatePassword: csi.password1, curateEmail: csi.email };
    var options = {};
    options.url = Uri.app('ph/createspace.php');
    options.dataType = 'json';
    options.data = args;
    options.type = 'GET';
    options.url += '?u=' + new Date().getTime();
    options.success = function(data, textStatus, request1) {
        var pr = data;
        if (pr != null && pr.result) {
            csi.activateId = pr.activateId;
            Site._sendThemMail(csi);
            Site._sendMeMail(csi);
            var host = Uri.front(window.location.href);
            host = host.substr(0, host.length - 'creator/pages'.length) + '/spaces';
            var url = String.format(Uri.join(ThemeBase.rootPath, 'spaces/{0}/Scripts/{1}?minimize=y'), csi.name, ThemeYoshi.masterScripts);
            new Await().loadScript(Uri.uniqueify(url)).addDx(function() {
                Cluster.spinner(false);
            }).addDx(function() {
                Exceptions.SaveLog('build', String.format('finished{0} time={1}ms', msg, new Date().getTime() - start));
            }).addAw(ss.Delegate.create(new Ask(), new Ask().okAw), String.format("Created new space \"{0}\"<br><br><span style='font-size:60%'>{1}</span><br><br>You will receive an email with an activation code for your new space.", csi.name, Uri.join(host, csi.name, ThemeYoshi.masterPage))).commit(awp);
            return;
        }
        Cluster.spinner(false);
        awp.done();
    };
    options.error = function(request, textStatus, error) {
        Cluster.spinner(false);
        Inform.error(String.format('Error creating space {0}, {1} {2}', csi.name, textStatus, error));
        awp.handle(new Error(Exceptions.blobLoadError));
    };
    $.ajax(options);
}


////////////////////////////////////////////////////////////////////////////////
// CreateSpaceItem

CreateSpaceItem = function CreateSpaceItem() {
    /// <field name="activateId" type="String">
    /// </field>
    /// <field name="createTime" type="Number" integer="true">
    /// </field>
    /// <field name="email" type="String">
    /// </field>
    /// <field name="emailEl" type="jQueryObject">
    /// </field>
    /// <field name="name" type="String">
    /// </field>
    /// <field name="nameEl" type="jQueryObject">
    /// </field>
    /// <field name="password1" type="String">
    /// </field>
    /// <field name="password1El" type="jQueryObject">
    /// </field>
    /// <field name="password2" type="String">
    /// </field>
    /// <field name="password2El" type="jQueryObject">
    /// </field>
}
CreateSpaceItem.prototype = {
    activateId: null,
    createTime: 0,
    email: null,
    emailEl: null,
    name: null,
    nameEl: null,
    password1: null,
    password1El: null,
    password2: null,
    password2El: null
}


////////////////////////////////////////////////////////////////////////////////
// SiteHelpers

SiteHelpers = function SiteHelpers() {
}
SiteHelpers.forVersion = function SiteHelpers$forVersion(site, fn) {
    /// <param name="site" type="String">
    /// </param>
    /// <param name="fn" type="System.Action`2">
    /// </param>
    var nm = 'Vx' + site;
    var url = Uri.join('../spaces', site, 'Scripts/Scripts/version.txt');
    if (site === 'root') {
        url = '../Scripts/Scripts/version.txt';
    }
    else if (!site.indexOf('../')) {
        url = Uri.join(site, 'Scripts/Scripts/version.txt');
    }
    new Await().loadJson(nm, Uri.uniqueify(url)).handleDl(Exceptions.blobLoadError, Await.finishAw).addDx(function() {
        var vx = Await.files[nm];
        fn(site, String.format('{0}.{1}.{2}', vx['version'], vx['revision'], vx['build']));
        delete Await.files[nm];
    }).commit();
}


////////////////////////////////////////////////////////////////////////////////
// Spaces

Spaces = function Spaces() {
    /// <field name="logSiteKey" type="String" static="true">
    /// </field>
}
Spaces.page = function Spaces$page() {
    SiteHelpers.forVersion('../creator', function(n, v) {
        $('#CreatorVersion').html('Creator Version ' + v);
    });
    SiteHelpers.forVersion('../', function(n, v) {
        $('#PlayNexusVersion').html('PlayNexus Version ' + v);
    });
    $('#UpdateAllBtn').click(Spaces.updateAllEv);
    new Await().addAw(FileBlobBase.getDirAw, '../../spaces').addDx(function(aw) {
        Site.map = aw.get_result();
        var host = Uri.front(window.location.href);
        host = host.substr(0, host.length - 'creator'.length);
        var el = $("<div id='SpacesList'/>").appendTo($('#Sites').empty());
        var body = $('<tbody/>').appendTo($('<table/>').appendTo(el));
        Spaces._addSiteRow(body, host, 'root');
        var $enum1 = ss.IEnumerator.getEnumerator(Site.map.dirs);
        while ($enum1.moveNext()) {
            var site = $enum1.current;
            Spaces._addSiteRow(body, host + '/spaces', site);
        }
    }).addDx(function() {
        if (ThemeYoshi.get_currentPage().Admin) {
            $('#LogOutput').closest('.Gig').hide();
        }
        if (window.location.hostname === 'love.playnexus.com') {
            $('#PublishLiveBtn').click(Spaces.publishLiveEv);
            $('#PublishLiveAllBtn').click(Spaces.publishLiveAllEv);
        }
        else {
            $('#PublishLiveBtn').attr('disabled', 'disabled').attr('title', 'only available on dev site');
            $('#PublishLiveAllBtn').attr('disabled', 'disabled').attr('title', 'only available on dev site');
        }
    }).commit();
}
Spaces._addSiteRow = function Spaces$_addSiteRow(body, host, site) {
    /// <param name="body" type="jQueryObject">
    /// </param>
    /// <param name="host" type="String">
    /// </param>
    /// <param name="site" type="String">
    /// </param>
    var tr = $('<tr/>').appendTo(body);
    $('<td/>').appendTo(tr).append($("<a class='Site' target='_blank'/>").html(site).attr({ href: Uri.join(host, site, ThemeYoshi.masterPage) }));
    $('<td/>').appendTo(tr).attr('id', 'Vx' + site);
    $("<td class='SpaceBtn UpdateBtn'/>").appendTo(tr).html('update').click(Spaces.updateSiteCv(site));
    $("<td class='SpaceBtn LogsBtn'/>").appendTo(tr).html('logs').click(Spaces.goToLogsCv(site));
    $('<td/>').appendTo(tr).append($("<div class='DelBtn'/>").html('\u2716').attr('title', 'delete this space').attr('id', 'DEL' + site).click(Site.spaceDelUx(site)));
    SiteHelpers.forVersion(site, function(n, v) {
        $('#Vx' + n).html(v);
    });
}
Spaces.goToLogsCv = function Spaces$goToLogsCv(site) {
    /// <param name="site" type="String">
    /// </param>
    /// <returns type="Function"></returns>
    return function(e) {
        DomElement.cancelEvent(e);
        Nsb.Storage.setSession('LogSite', site);
        Master.GoPage(ThemeYoshi.defaultPageClass, 'syslogs');
    };
}
Spaces.updateAllEv = function Spaces$updateAllEv(e) {
    /// <param name="e" type="jQueryEvent">
    /// </param>
    var $enum1 = ss.IEnumerator.getEnumerator(Site.map.dirs);
    while ($enum1.moveNext()) {
        var site = $enum1.current;
        var fn = Spaces.updateSiteCv(site);
        fn(e);
    }
}
Spaces.updateSiteCv = function Spaces$updateSiteCv(site) {
    /// <param name="site" type="String">
    /// </param>
    /// <returns type="Function"></returns>
    return function(e) {
        DomElement.cancelEvent(e);
        var csi = new CreateSpaceItem();
        csi.name = site;
        Spaces.updateSpaceAw(Await.get_asyncAw(), csi);
    };
}
Spaces.updateSpaceAw = function Spaces$updateSpaceAw(awp, csi) {
    /// <param name="awp" type="Await">
    /// </param>
    /// <param name="csi" type="CreateSpaceItem">
    /// </param>
    var start = new Date().getTime();
    var msg = String.format(' - updating space name={0}', csi.name);
    Inform.event('Spaces.UpdateSpaceAw', msg);
    Exceptions.SaveLog('build', 'beginning' + msg);
    Cluster.spinner(true, 0.35);
    csi.createTime = new Date().getTime();
    var args = { password: Nsb.Storage.getLocal(ThemeYoshi.get_curatePasswordKey()), spaceName: csi.name, update: true };
    var options = {};
    options.url = Uri.app('ph/createspace.php');
    options.dataType = 'json';
    options.data = args;
    options.type = 'GET';
    options.success = function(data, textStatus, request1) {
        Cluster.spinner(false);
        var result = data;
        if (result['result']) {
            SiteHelpers.forVersion(csi.name, function(n, v) {
                $('#Vx' + n).html(v);
            });
            var url = String.format('../spaces/{0}/Scripts/{1}?minimize=y', csi.name, ThemeYoshi.masterScripts);
            new Await().loadScript(Uri.uniqueify(url)).addDx(function() {
                Exceptions.SaveLog('build', String.format('finished{0} time={1}ms', msg, new Date().getTime() - start));
            }).commit(awp);
            return;
        }
        awp.done();
    };
    options.error = function(request, textStatus, error) {
        Cluster.spinner(false);
        Inform.error(String.format('Error creating space {0}, {1} {2}', csi.name, textStatus, error));
        awp.handle(new Error(Exceptions.blobLoadError));
    };
    $.ajax(options);
}
Spaces.publishLiveEv = function Spaces$publishLiveEv(e) {
    /// <param name="e" type="jQueryEvent">
    /// </param>
    DomElement.cancelEvent(e);
    Spaces.publishLive({});
}
Spaces.publishLiveAllEv = function Spaces$publishLiveAllEv(e) {
    /// <param name="e" type="jQueryEvent">
    /// </param>
    DomElement.cancelEvent(e);
    Spaces.publishLive({ alldata: true });
}
Spaces.publishLive = function Spaces$publishLive(opts) {
    /// <param name="opts" type="Object">
    /// </param>
    new Await().addAw(ss.Delegate.create(new Ask(), new Ask().okCancelAw), { Msg: String.format('Publish {0} for sure?', (opts['alldata']) ? 'ALL' : 'software') }).addAw(DomElement.requireResultAw, true).addDx(function(aw) {
        var start = new Date().getTime();
        var msg = String.format(' - publishing to PlayNexus');
        Inform.debug(msg);
        Exceptions.SaveLog('build', 'beginning' + msg);
        Cluster.spinner(true, 0.35);
        var args = { password: Nsb.Storage.getLocal(ThemeYoshi.get_curatePasswordKey()) };
        args = $.extend(args, opts);
        var options = {};
        options.url = Uri.app('ph/publishpnx.php');
        options.dataType = 'json';
        options.data = args;
        options.type = 'GET';
        options.success = function(data, textStatus, request1) {
            var result = data;
            $('#LogOutput').html(Transform.htmlize(Rx.prettyJson(data))).closest('.Gig').show();
            if (result['result']) {
                var url1 = String.format('http://www.playnexus.com/Scripts/{0}?minimize=y', ThemeYoshi.masterScripts);
                var url2 = String.format('http://www.playnexus.com/creator/Scripts/{0}?minimize=y', ThemeYoshi.masterScripts);
                new Await().loadScript(Uri.uniqueify(url1)).loadScript(Uri.uniqueify(url2)).addDx(function() {
                    Cluster.spinner(false);
                }).addDx(function() {
                    Exceptions.SaveLog('build', String.format('finished{0} time={1}ms', msg, new Date().getTime() - start));
                }).commit(aw);
                return;
            }
            aw.done();
        };
        options.error = function(request, textStatus, error) {
            Cluster.spinner(false);
            Inform.error(String.format('Error publishing live {0} {1}', textStatus, error));
            aw.done();
        };
        $.ajax(options);
    }).commit();
}


GigForms.registerClass('GigForms');
LogsPage.registerClass('LogsPage');
PlaySpace.Classes.LogItem.registerClass('PlaySpace.Classes.LogItem');
Scroller.registerClass('Scroller');
Site.registerClass('Site');
CreateSpaceItem.registerClass('CreateSpaceItem');
SiteHelpers.registerClass('SiteHelpers');
Spaces.registerClass('Spaces');
GigForms.keysKey = 'kk';
GigForms.isPwKey = 'ip';
GigForms.validateException = 'ValidateException';
GigForms._cloneProps = [ 'font-family', 'font-color', 'font-size', 'padding-left', 'padding-right', 'padding-top', 'padding-bottom', 'width', 'height', 'color', 'background-color', 'border-top-left-radius', 'border-top-right-radius', 'border-bottom-left-radius', 'border-bottom-right-radius' ];
LogsPage._headers = { d: 'date', m: 'message', b: 'browser', u: 'url' };
LogsPage._logSite = '';
Site.spacesPath = '../../spaces';
Site.passwordMatchMsg = "passwords don't match";
Site.spaceNameShortMsg = 'space name must be at least 4 characters long';
Site.spaceNameLongMsg = 'space name must be less than 20 characters long';
Site.spaceNameLowerMsg = 'space name must be all lower case';
Site.spaceNameLettersMsg = 'space name can only contain letters, numbers, and underscore and must start with a letter';
Site.emailValidMsg = 'please enter a valid email address';
Site.passwordLengthMsg = 'password must be at least 8 characters long';
Site.incorrectMathMsg = 'incorrect math result';
Site._sendTo = window.localStorage.getItem('DevEmailTo') || 'nsbawden@gmail.com';
Site.map = null;
Site._validateEl = null;
Spaces.logSiteKey = 'LogSite';
})();

//! This script was generated using Script# v0.7.4.0
